from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.model_selection import train_test_split
import numpy as np

# 加载20Newsgroups数据集，这里只选取了部分类别作为示例
categories = ['alt.atheism', 'soc.religion.christian', 'comp.graphics', 'sci.med']
news = fetch_20newsgroups(subset='all', categories=categories)

# 查看数据集中的文本数据和对应的标签
X = news.data
y = news.target

# 文本特征提取
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(X)

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 构建朴素贝叶斯分类器并进行训练
clf = MultinomialNB()
clf.fit(X_train, y_train)
# 模型评估
y_pred = clf.predict(X_test)
accuracy = np.mean(y_pred == y_test)
print("模型准确率:", accuracy)